package com.xzakota.minesweeper.msg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息处理器工厂
 *
 * @author Xzakota
 */
public class MsgHandlerFactory {
    public static final Class<? extends BaseMsg> MSG_TYPE_SIGN_IN = SignInMsg.class;
    public static final Class<? extends BaseMsg> MSG_TYPE_SIGN_UP = SignUpMsg.class;
    public static final Class<? extends BaseMsg> MSG_TYPE_SIGN_OUT = SignOutMsg.class;
    public static final Class<? extends BaseMsg> MSG_TYPE_GAME_ALL_ROOM = GameAllRoomMsg.class;
    public static final Class<? extends BaseMsg> MSG_TYPE_ENTER_ROOM = UserEnterRoomMsg.class;
    public static final Class<? extends BaseMsg> MSG_TYPE_ROOM_RANK = RoomRankMsg.class;

    private static final Map<Class<? extends BaseMsg>, List<MsgHandler>> HANDLERS;

    static {
        HANDLERS = new HashMap<>();

        HANDLERS.put(MSG_TYPE_SIGN_IN, new ArrayList<>());
        HANDLERS.put(MSG_TYPE_SIGN_UP, new ArrayList<>());
        HANDLERS.put(MSG_TYPE_SIGN_OUT, new ArrayList<>());
        HANDLERS.put(MSG_TYPE_GAME_ALL_ROOM, new ArrayList<>());
        HANDLERS.put(MSG_TYPE_ENTER_ROOM, new ArrayList<>());
        HANDLERS.put(MSG_TYPE_ROOM_RANK, new ArrayList<>());

        addMsgHandler(MSG_TYPE_SIGN_IN, new SignInMsgDefaultHandler());
        addMsgHandler(MSG_TYPE_SIGN_UP, new SignUpMsgDefaultHandler());
        addMsgHandler(MSG_TYPE_SIGN_OUT, new SignOutMsgDefaultHandler());
        addMsgHandler(MSG_TYPE_GAME_ALL_ROOM, new GameAllRoomMsgMsgDefaultHandler());
        addMsgHandler(MSG_TYPE_ENTER_ROOM, new UserEnterRoomMsgDefaultHandler());
    }

    public static List<MsgHandler> createMsgHandlers(BaseMsg msg) {
        return HANDLERS.get(msg.getClass());
    }

    public static void addMsgHandler(Class<? extends BaseMsg> clazz, MsgHandler handler) {
        List<MsgHandler> handlerList = HANDLERS.get(clazz);
        handlerList.add(handler);
    }

    public static void removeMsgHandler(Class<? extends BaseMsg> clazz, MsgHandler handler) {
        List<MsgHandler> handlerList = HANDLERS.get(clazz);
        handlerList.removeIf(msgHandler -> msgHandler == handler);
    }
}
